package com.yanqu.road.server.cmd.activity.shuihu;

import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.activity.ShuiHuActivityProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.cross.battle.ShuiHuActivity;
import com.yanqu.road.server.manager.cross.battle.ShuiHuMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;

import java.util.List;

@Cmd(code = CrossProtocol.C2_SHUIHU_ACTIVITY_DRAW_CARD, desc = "跨服抽卡")
public class CrossShuiHuDrawCardCmd extends CrossCommand {

    private int activityId;
    private long userId;
    private long serverId;
    private int itemNo;
    private int roundNo;
    private PlayerProto.PlayerBaseTempMsg player;

    private int cardId;

    private ShuiHuActivity activity = null;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        ShuiHuActivityProto.CrossDrawCardReqMsg reqMsg = ShuiHuActivityProto.CrossDrawCardReqMsg.parseFrom(packet.getBytes());
        activityId = reqMsg.getActivityId();
        userId = reqMsg.getUserId();
        serverId = reqMsg.getServerId();
        itemNo = reqMsg.getItemNo();
        roundNo = reqMsg.getRoundNo();
        player = reqMsg.getPlayer();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        activity = ShuiHuMgr.getActivity(activityId);
        if (activity == null) {
            ret = GameErrorCode.E_SHUIHU_ACTIVITY_NO_OPEN;
            return;
        }

        List<Integer> result = activity.drawCard(itemNo, roundNo, userId, PlayerBasePb.parseToUserBaseInfo(player));
        ret = result.get(0);
        if (ret == 0) {
            cardId = result.get(1);
        }
    }

    @Override
    public void sendData() {
        ShuiHuActivityProto.CrossDrawCardRespMsg.Builder builder = ShuiHuActivityProto.CrossDrawCardRespMsg.newBuilder();
        builder.setRet(ret);
        if (ret == 0) {
            builder.setCardId(cardId);
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(GameProtocol.S_SHUIHU_ACTIVITY_DRAW_CARD_FROM_CROSS, builder));

        // 发送开启数据
        if (activity != null && activity.needAdvanceSyncDraw()) {
            activity.syncDrawMsgList(true);
        }
    }
}
